const { Readable } = require("stream");
const _ = require("lodash");
const fs = require("fs");
const path = require("path");
const moment = require("moment");
const utils = require('../../utils');

module.exports = async function (dir, { type, format } = {}) {
  const stream = new Readable({ objectMode: true });
  format = utils.parseFunction(format);
  const files = fs.readdirSync(dir);
  let list = [], rowNo = 0;
  for (const file of files) {
    const fullname = path.join(dir, file).replace(/\\/g, '/');
    const info = fs.statSync(fullname);
    if(info.isDirectory()) {
      list.push({ isdir: true, name: file, fullname });
    } else {
      const extname = path.extname(file);
      const purename = extname ? file.replace(extname, '') : file;
      list.push({ name: file, extname, purename, fullname });
    }
  }
  if (type === 1) {
    list = list.filter(o=>o.isdir);
  } else if (type === 2) {
    list = list.filter(o=>!o.isdir);
  }
  list = format ? await format(list, { _, moment, utils }) : list;

  stream._read = async function () {
    if (rowNo < list.length) {
      stream.push(list[rowNo]);
    } else {
      stream.push(null);
    }
    rowNo++;
  };
  stream.on('end', () => {
    utils.debug('dirReader [end]');
  });
  
  return stream;
}